#include "gettraff.h"

GetTraff::GetTraff(const QString &__iface, bool resetValue, QObject *parent) : QObject(parent)
{
    rx0 = tx0 = 0;
    iface = __iface;

    if( resetValue ) {
        TraffData valueTraff = this->getCurrBytesAbs();
        rx0 = valueTraff.rx;
        tx0 = valueTraff.tx;
    }
}

TraffData GetTraff::getCurrBytesAbs()
{
    TraffData retValue;
    QString strRxFile = QString( "/sys/class/net/" ) + iface + QString( "/statistics/rx_bytes" );
    QString strTxFile = QString( "/sys/class/net/" ) + iface + QString( "/statistics/tx_bytes" );
    QFile rxFile( strRxFile );
    QFile txFile( strTxFile );

    if ( ! rxFile.open(QIODevice::ReadOnly|QIODevice::Text) ) {
        retValue.ok = false;
        retValue.rx = 0;
        retValue.tx = 0;
        return retValue;
    }

    if ( ! txFile.open(QIODevice::ReadOnly|QIODevice::Text) ) {
        retValue.ok = false;
        retValue.rx = 0;
        retValue.tx = 0;
        return retValue;
    }

    QByteArray line = rxFile.readLine();
    bool ok;
    retValue.rx = QString(line).toInt(&ok);
    rxFile.close();

    line = txFile.readLine();
    retValue.tx = QString(line).toInt(&ok);
    txFile.close();

    retValue.ok = true;

    return retValue;
}


TraffData GetTraff::getCurrBytes()
{
    TraffData retValue;

    retValue = this->getCurrBytesAbs();

    retValue.rx = retValue.rx - rx0;
    retValue.tx = retValue.tx - tx0;

    return retValue;
}


QString GetTraff::ifaceExists() const
{
    QString addr = "";
    QString strPathFile = QString( "/sys/class/net/" ) + iface + QString("/address");
    QFile addrFile(  strPathFile );
    if ( ! addrFile.open(QIODevice::ReadOnly) ) {
        return addr;
    }

    QTextStream fs(&addrFile);
    addr = fs.readLine();
    addrFile.close();

    return addr;
}
